<?php

class Rzd_Validate_RequiredFieldsInMultiDynamic extends Zend_Validate_Abstract
{
    protected $_requiredFields;
    protected $_requiredNames;

    const FIELDS_ARE_NOT_FILLED = 'FieldsAreNotFilled';

    protected $_messageTemplates = array(
        self::FIELDS_ARE_NOT_FILLED =>
            "One of fields isn't filled Required fields: %value%",
    );

    public function __construct($options)
    {
        $this->_requiredFields = $options['requiredFields'];
        $this->_requiredFieldsNames = $options['requiredFieldsName'];
    }

    public function isValid($values)
    {
        foreach($values['data'] as $index => $fields) {
            $fillingFields = array_filter($fields);
            if(count($fillingFields)) {
                $keys = array_keys($fillingFields);
                $noFillingFields = array_diff($this->_requiredFields, $keys);

                if(count($noFillingFields)) {
                    $isValid = false;
                    $this->_setValue($this->_requiredFieldsNames);
                    $this->_error(self::FIELDS_ARE_NOT_FILLED);
                    return false;
                }
            }
        }

        return true;
    }
}
